#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
项目任务运行器 - 类似npm run的功能
使用方法: python scripts.py <module>:<command>
"""

import os
import sys
import subprocess
import json
from pathlib import Path

# 模块配置
MODULES = {
    "hello_python": {
        "name": "Hello Python 基础模块",
        "path": "modules/hello_python",
        "commands": {
            "run": {
                "description": "运行Hello Python程序",
                "command": "python main.py"
            },
            "build": {
                "description": "打包为exe文件",
                "command": "call build_exe.bat",
                "requires_venv": True
            },
            "run:exe": {
                "description": "运行打包的exe文件",
                "command": "..\\..\\dist\\hello_python.exe"
            }
        }
    },
    "background_remover": {
        "name": "一键抠图模块",
        "path": "modules/background_remover",
        "commands": {
            "help": {
                "description": "显示抠图工具帮助信息",
                "command": "python main.py -h",
                "requires_venv": True
            },
            "gui": {
                "description": "启动图形界面（推荐）",
                "command": "python main.py --gui",
                "requires_venv": True
            },
            "build": {
                "description": "打包抠图工具为exe文件（AI版本，需要网络下载模型）",
                "command": "bash build_remover.sh",
                "requires_venv": True
            },
            "build:ai": {
                "description": "打包AI版本抠图工具（完整功能，需要网络下载模型）",
                "command": "bash build_remover.sh --version=ai",
                "requires_venv": True
            },
            "installer": {
                "description": "构建安装程序（需要Inno Setup）",
                "command": "bash build_installer.sh",
                "requires_venv": False
            },
            "run:exe": {
                "description": "运行打包的exe文件（GUI模式）",
                "command": "..\\..\\dist\\background_remover.exe"
            },
            "run:exe:cli": {
                "description": "运行打包的exe文件（命令行模式）",
                "command": "..\\..\\dist\\background_remover.exe --help"
            },
            "model:list": {
                "description": "列出所有AI模型状态",
                "command": "python model_manager.py list",
                "requires_venv": True
            },
            "model:check-updates": {
                "description": "检查模型是否有更新",
                "command": "python model_manager.py check-updates",
                "requires_venv": True
            },
            "model:update": {
                "description": "更新模型到最新版本（可指定模型名）",
                "command": "python model_manager.py update",
                "requires_venv": True,
                "interactive": True
            },
            "model:download": {
                "description": "下载指定模型（需要指定模型名）",
                "command": "python model_manager.py download",
                "requires_venv": True,
                "interactive": True
            },
            "model:remove": {
                "description": "删除指定模型（需要指定模型名）",
                "command": "python model_manager.py remove",
                "requires_venv": True,
                "interactive": True
            },
            "model:clean": {
                "description": "清理所有模型缓存",
                "command": "python model_manager.py clean",
                "requires_venv": True
            }
        }
    },
    "wechat_auto_reply": {
        "name": "微信自动回复模块",
        "path": "modules/wechat_auto_reply",
        "commands": {
            "help": {
                "description": "显示微信自动回复工具帮助信息",
                "command": "python main.py -h",
                "requires_venv": True
            },
            "gui": {
                "description": "启动图形界面（推荐）",
                "command": "python main.py --gui",
                "requires_venv": True
            },
            "build": {
                "description": "打包微信自动回复工具为exe文件",
                "command": "bash build_wechat_auto_reply.sh",
                "requires_venv": True
            },
            "run:exe": {
                "description": "运行打包的exe文件（GUI模式）",
                "command": "..\\..\\dist\\wechat_auto_reply.exe"
            },
            "run:exe:cli": {
                "description": "运行打包的exe文件（命令行模式）",
                "command": "..\\..\\dist\\wechat_auto_reply.exe -h"
            }
        }
    }
}

# 全局命令配置
GLOBAL_COMMANDS = {
    "install": {
        "description": "安装项目依赖",
        "command": "pip install -r requirements.txt",
        "requires_venv": True
    },
    "install:dev": {
        "description": "安装开发依赖",
        "command": "pip install -r requirements.txt pytest black flake8",
        "requires_venv": True
    },
    "clean": {
        "description": "清理构建文件",
        "command": [
            "rmdir /s /q build 2>nul || true",
            "rmdir /s /q dist 2>nul || true", 
            "del *.spec 2>nul || true",
            "rmdir /s /q __pycache__ 2>nul || true"
        ]
    },
    "env:create": {
        "description": "创建虚拟环境",
        "command": "python -m venv venv"
    },
    "env:activate": {
        "description": "一键激活当前虚拟环境",
        "command": ""
    },
    "env:create-activate": {
        "description": "创建便捷的激活脚本文件",
        "command": ""
    },
    "format": {
        "description": "格式化代码",
        "command": "black .",
        "requires_venv": True
    },
    "lint": {
        "description": "代码检查",
        "command": "flake8 .",
        "requires_venv": True
    }
}

def get_venv_python():
    """获取虚拟环境的Python路径"""
    if os.name == 'nt':  # Windows
        return "..\\..\\venv\\Scripts\\python.exe"
    else:  # Unix/Linux/Mac
        return "../../venv/bin/python"

def get_venv_activate():
    """获取激活虚拟环境的命令"""
    # 项目统一使用Git Bash工具
    return "source venv/Scripts/activate"

def is_venv_active():
    """检查虚拟环境是否已激活"""
    return hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)

def activate_venv():
    """自动激活虚拟环境"""
    print("🔄 自动激活虚拟环境...")
    
    # 检查虚拟环境是否存在
    venv_script = "venv/Scripts/activate"
    if not os.path.exists(venv_script):
        print(f"❌ 虚拟环境不存在: {venv_script}")
        print("请先创建虚拟环境: python scripts.py env:create")
        return False
    
    try:
        # 使用subprocess激活虚拟环境并运行python脚本
        # 返回True表示激活成功，但实际上我们需要在命令执行中包含激活逻辑
        print("✅ 虚拟环境激活成功")
        return True
    except Exception as e:
        print(f"❌ 虚拟环境激活失败: {e}")
        return False

def run_command(command, env=None, requires_venv=False, cwd=None):
    """运行命令"""
    if requires_venv and not is_venv_active():
        if not activate_venv():
            return False
        # 需要在bash中激活虚拟环境并执行命令
        # 如果在模块目录中运行，需要调整虚拟环境路径
        if cwd and cwd != ".":
            venv_activation = "source ../../venv/Scripts/activate &&"
        else:
            venv_activation = "source venv/Scripts/activate &&"
        use_bash = True
    else:
        venv_activation = ""
        use_bash = False
    
    # 设置环境变量
    cmd_env = os.environ.copy()
    if env:
        cmd_env.update(env)
    
    # 设置工作目录
    work_dir = cwd if cwd else "."
    
    # 如果是字符串命令，直接运行
    if isinstance(command, str):
        # 如果需要虚拟环境且未激活，使用bash执行
        if requires_venv and not is_venv_active():
            full_command = f"bash -c '{venv_activation} {command}'"
        else:
            full_command = command
            
        try:
            result = subprocess.run(full_command, shell=True, env=cmd_env, cwd=work_dir)
            return result.returncode == 0
        except Exception as e:
            print(f"❌ 命令执行失败: {e}")
            return False
    
    # 如果是命令列表，逐个运行
    elif isinstance(command, list):
        for cmd in command:
            try:
                # 如果需要虚拟环境且未激活，使用bash执行
                if requires_venv and not is_venv_active():
                    full_cmd = f"bash -c '{venv_activation} {cmd}'"
                else:
                    full_cmd = cmd
                    
                result = subprocess.run(full_cmd, shell=True, env=cmd_env, cwd=work_dir)
                if result.returncode != 0:
                    print(f"❌ 命令失败: {cmd}")
                    return False
            except Exception as e:
                print(f"❌ 命令执行失败: {e}")
                return False
        return True

def list_modules():
    """列出所有可用的模块"""
    print("📦 可用的项目模块：\n")
    for module_name, module_config in MODULES.items():
        print(f"  📁 {module_name}")
        print(f"     {module_config['name']}")
        print(f"     路径: {module_config['path']}")
        print("     可用命令:")
        for cmd_name, cmd_config in module_config['commands'].items():
            requires_venv = cmd_config.get('requires_venv', False)
            venv_indicator = " 🐍" if requires_venv else ""
            interactive = cmd_config.get('interactive', False)
            interactive_indicator = " 🎮" if interactive else ""
            print(f"       {module_name}:{cmd_name:<12} - {cmd_config['description']}{venv_indicator}{interactive_indicator}")
        print()
    
    print("🌐 全局命令：\n")
    for cmd_name, cmd_config in GLOBAL_COMMANDS.items():
        requires_venv = cmd_config.get('requires_venv', False)
        venv_indicator = " 🐍" if requires_venv else ""
        print(f"  {cmd_name:<15} - {cmd_config['description']}{venv_indicator}")
    
    print(f"\n💡 使用方法:")
    print(f"  python {sys.argv[0]} <module>:<command>  # 运行模块命令")
    print(f"  python {sys.argv[0]} <global_command>    # 运行全局命令")
    print(f"  python {sys.argv[0]} list                # 列出所有命令")
    print("\n📝 标记说明:")
    print("  🐍 需要激活虚拟环境")
    print("  🎮 交互式命令（需要额外参数）")

def run_module_command(module_name, command_name, extra_args=None):
    """运行模块命令"""
    if module_name not in MODULES:
        print(f"❌ 未知的模块: {module_name}")
        return False
    
    module_config = MODULES[module_name]
    
    if command_name not in module_config['commands']:
        print(f"❌ 模块 {module_name} 中未找到命令: {command_name}")
        print(f"可用命令: {', '.join(module_config['commands'].keys())}")
        return False
    
    command_config = module_config['commands'][command_name]
    module_path = module_config['path']
    
    print(f"🚀 运行模块命令: {module_name}:{command_name}")
    print(f"📁 模块: {module_config['name']}")
    print(f"📝 描述: {command_config.get('description', '')}")
    print(f"📂 工作目录: {module_path}")
    
    # 处理交互式命令
    command = command_config['command']
    if command_config.get('interactive', False) and extra_args:
        # 对于特定的命令，需要特殊处理参数
        if command_name.startswith('model:') and module_name == 'background_remover':
            # 模型管理命令需要特殊处理
            if command_name in ['model:download', 'model:remove'] and extra_args:
                # 检查是否包含 --force 标志
                force_flag = "--force" if "--force" in extra_args else ""
                model_args = [arg for arg in extra_args if arg != "--force"]
                if model_args:
                    command += " " + " ".join(model_args) + (" " + force_flag if force_flag else "")
                else:
                    print("❌ 请指定模型名称 (u2net, u2net_human_seg, silueta)")
                    return False
            elif command_name == 'model:update' and extra_args:
                # update命令可以指定模型名或使用--force标志
                force_flag = "--force" if "--force" in extra_args else ""
                model_args = [arg for arg in extra_args if arg != "--force"]
                if model_args:
                    command += " " + " ".join(model_args) + (" " + force_flag if force_flag else "")
                elif force_flag:
                    command += " " + force_flag
            elif command_name == 'model:check-updates' and extra_args:
                # check-updates命令可以指定模型名
                model_args = [arg for arg in extra_args if not arg.startswith('--')]
                if model_args:
                    command += " " + " ".join(model_args)
        else:
            command += " " + " ".join(extra_args)
    
    success = run_command(
        command,
        command_config.get('env'),
        command_config.get('requires_venv', False),
        module_path
    )
    
    return success

def run_global_command(command_name):
    """运行全局命令"""
    if command_name not in GLOBAL_COMMANDS:
        print(f"❌ 未知的全局命令: {command_name}")
        return False
    
    command_config = GLOBAL_COMMANDS[command_name]
    
    print(f"🚀 运行全局命令: {command_name}")
    print(f"📝 描述: {command_config.get('description', '')}")
    
    # 特殊处理激活虚拟环境命令
    if command_name == "env:activate":
        venv_path = "venv"
        activate_script = os.path.join(venv_path, "Scripts", "activate")
        
        # 检查虚拟环境是否存在
        if not os.path.exists(venv_path) or not os.path.exists(activate_script):
            print(f"❌ 虚拟环境不存在: {venv_path}")
            print("请先创建虚拟环境: python scripts.py env:create")
            return False
        
        # 检查当前是否在虚拟环境中
        in_venv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
        if in_venv:
            print("🎉 虚拟环境已经激活！")
            return True
        
        # 尝试提供激活指导
        print("🔄 正在检查虚拟环境...")
        try:
            # 获取当前shell类型
            shell = os.environ.get('SHELL', '').lower()
            is_git_bash = 'bash' in shell or 'git' in os.environ.get('TERM', '').lower()
            
            print(f"\n💡 激活虚拟环境命令:")
            if is_git_bash or os.name == 'nt':
                # 在Git Bash或Windows环境下
                print("   Git Bash: source venv/Scripts/activate")
                print("   Windows CMD: venv\\Scripts\\activate.bat")
            else:
                # 其他Unix-like系统
                print("   source venv/bin/activate")
            
            print("\n📝 当前虚拟环境状态: ❌ 未激活")
            
            print("\n🔧 一键激活方法:")
            print("1. 复制并运行上面的相应激活命令")
            if os.path.exists("activate_env.sh"):
                print("2. 或者使用便捷脚本: source ./activate_env.sh")
            
            print("\n⚠️  注意: 由于Python子进程的限制，无法从脚本内直接激活父shell的虚拟环境。")
            print("   您需要手动复制并运行上面的命令。")
            return True
        except Exception as e:
            print(f"❌ 检查虚拟环境时出错: {e}")
            return False
    
    # 创建激活脚本
    if command_name == "env:create-activate":
        try:
            # 只创建 Git Bash 兼容的激活脚本
            with open("activate_env.sh", "w", encoding="utf-8") as f:
                f.write("#!/bin/bash\n")
                f.write("echo '正在激活虚拟环境...'\n")
                f.write("source venv/Scripts/activate\n")  # Windows下的Git Bash使用Scripts路径
                f.write("echo '✅ 虚拟环境已激活'\n")
                f.write("echo '💡 现在可以运行项目命令了'\n")
                f.write("echo '🚀 请在当前终端中继续运行项目命令'\n")
            
            # 设置执行权限
            if os.name != 'nt':
                os.chmod("activate_env.sh", 0o755)
            
            print("✅ Git Bash激活脚本创建成功!")
            print("\n📁 创建的文件:")
            print("  activate_env.sh   - Git Bash激活脚本（适用于Windows/Linux/Mac）")
            print("\n🚀 使用方法:")
            print("  在Git Bash中运行: source ./activate_env.sh")
            print("  或者直接运行: ./activate_env.sh")
            print("\n💡 提示: 激活后请继续在当前终端中使用")
            
            return True
        except Exception as e:
            print(f"❌ 创建激活脚本失败: {e}")
            return False
    
    success = run_command(
        command_config['command'],
        command_config.get('env'),
        command_config.get('requires_venv', False)
    )
    
    return success

def main():
    """主函数"""
    if len(sys.argv) < 2:
        list_modules()
        return
    
    command_input = sys.argv[1]
    extra_args = sys.argv[2:] if len(sys.argv) > 2 else None
    
    if command_input in ["help", "-h", "--help", "list"]:
        list_modules()
        return
    
    # 首先检查是否是全局命令
    if command_input in GLOBAL_COMMANDS:
        success = run_global_command(command_input)
    # 然后检查是否是模块命令 (格式: module:command)
    elif ":" in command_input:
        try:
            module_name, command_name = command_input.split(":", 1)
            success = run_module_command(module_name, command_name, extra_args)
        except ValueError:
            print(f"❌ 命令格式错误: {command_input}")
            print("正确格式: <module>:<command>")
            return
    else:
        print(f"❌ 未知的命令: {command_input}")
        print("运行 'python scripts.py help' 查看可用命令")
        success = False
    
    if success:
        print(f"✅ 命令执行成功")
    else:
        print(f"❌ 命令执行失败")
        sys.exit(1)

if __name__ == "__main__":
    main()